package com.wondersgroup.insurance.datalibrary;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *  functions to simplifiy common {@link MessageDigest} tasks.  This
 * class is thread safe.
 * 
 * @author pengjiong
 *
 */
public class MD5Util {

	private static MD5Util instance;
	
	public static MD5Util get() {
		if(instance == null ){
			instance = new MD5Util(); 
		}
		return instance;
	}
    /**
     * Returns a MessageDigest for the given <code>algorithm</code>.
     * 
     * @param
     *            The MessageDigest algorithm name.
     * @return An MD5 digest instance.
     * @throws RuntimeException
     *             when a {@link NoSuchAlgorithmException} is
     *             caught
     */

    private MessageDigest getDigest() {
        try {
            return MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Calculates the MD5 digest and returns the value as a 16 element
     * <code>byte[]</code>.
     * 
     * @param data
     *            Data to digest
     * @return MD5 digest
     */
    public  byte[] md5(byte[] data) {
        return getDigest().digest(data);
    }

    /**
     * Calculates the MD5 digest and returns the value as a 16 element
     * <code>byte[]</code>.
     * 
     * @param data
     *            Data to digest
     * @return MD5 digest
     */
    public  byte[] md5(String data) {
        return md5(data.getBytes());
    }

    /**
     * Calculates the MD5 digest and returns the value as a 32 character hex
     * string.
     * 
     * @param data
     *            Data to digest
     * @return MD5 digest as a hex string
     */
    public  String md5Hex(byte[] data) {
        return HexUtil.get().toHexString(md5(data));
    }

    /**
     * Calculates the MD5 digest and returns the value as a 32 character hex
     * string.
     * 
     * @param data
     *            Data to digest
     * @return MD5 digest as a hex string
     */
    public  String md5Hex(String data) {
        return  HexUtil.get().toHexString(md5(data));
    }
    
    /**
     * 16位的md5
     * @param data
     * @return
     */
    public String md5Hex16(String data){
    	return  HexUtil.get().toHexString(md5(data)).substring(8, 24);
    }
  
}
